#include <string.h>
#include <sys/time.h>

#include "GContext.h"
#include "GBitmap.h"
#include "GColor.h"

int main(int argc, char** argv) {
    const int W = 100;
    const int H = 100;

    const int LOOP_CLEAR = 20;
    const int LOOP_GET_BITMAP = 1;

    timeval start_t, end_t, diff_t;

    const GColor color = { 1, 1, 0, 0 };
    const GPixel pixel = 0xFFFF0000;

    GContext* ctx;

    ctx = GContext::Create(W, H);
    if (!ctx) {
      fprintf(stderr, "GContext::Create failed\n");
      return -1;
    }
      
    gettimeofday(&start_t, NULL);

    for (int i = 0; i < LOOP_CLEAR; ++i) { 
      // clear bitmap to red
      ctx->clear(color);
    }

    gettimeofday(&end_t, NULL);
    timersub(&end_t, &start_t, &diff_t);
    printf("Clear took %f us per pixel.\n", ((double) diff_t.tv_sec * 1000000 + diff_t.tv_usec) / ((double) H * W * LOOP_CLEAR));

    GBitmap bitmap;

    for (int i = 0; i < LOOP_GET_BITMAP; ++i) { 
      ctx->getBitmap(&bitmap);
    }

    // check pixel values for correctness
    for (int y = 0; y < W; ++y) {
        const char* row = (const char*)bitmap.fPixels + bitmap.fRowBytes * y;
        for (int x = 0; x < H; ++x) {
            const GPixel value = ((const GPixel*)row)[x];
            if (pixel != value) {
                fprintf(stderr, "at (%d, %d) expected %x but got %x\n",
                        x, y, pixel, value);
                return -1;
            }
        }
    }

    delete ctx;
    fprintf(stderr, "passed.\n");
    return 0;
}

